<template>
  <div class="flex flex-col h-full overflow-hidden">
    <app-header/>

    <main>
      <h2 class="page-title">用户管理</h2>

      <div class="top-bar">
        <button id="btn-add-user" class="hmi-button hmi-button-primary" @click="goToAddUserPage">
          <i class="fas fa-user-plus"></i> 新增用户
        </button>
        <div class="filter-input-container">
          <i class="fas fa-search"></i>
          <input type="text" id="user-table-search" v-model="searchTerm" placeholder="搜索工号或姓名..."
                 @input="filterUserTable">
        </div>
      </div>

      <div class="user-table-container">
        <table class="user-table">
          <thead>
          <tr>
            <th class="col-opid">工号/用户名</th>
            <th class="col-name">姓名</th>
            <th class="col-actions">操作</th>
          </tr>
          </thead>
          <tbody id="user-table-body">
          <tr
              v-for="user in filteredUserData"
              :key="user.id"
              :data-user-id="user.id"
              :class="{ 'highlight': user.highlight }"
          >
            <td class="col-opid">{{ user.opid }}</td>
            <td class="col-name">{{ user.name || '-' }}</td>
            <td class="col-actions">
              <button class="action-button edit" title="编辑" @click="goToEditUserPage(user.id)">
                <i class="fas fa-edit"></i>
              </button>
              <button class="action-button delete" title="删除" @click="goToDeleteUserConfirmPage(user.id, user.opid)">
                <i class="fas fa-trash"></i>
              </button>
            </td>
          </tr>
          <tr v-if="filteredUserData.length === 0">
            <td colspan="3" class="px-3 py-4 text-center text-[var(--text-secondary)]">无匹配的用户记录</td>
          </tr>
          </tbody>
        </table>
      </div>
    </main>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed, onUnmounted} from 'vue'
import {useRouter} from 'vue-router'

const router = useRouter()

// --- 响应式数据 ---
const userData = reactive([])
const searchTerm = ref('')
const isLoading = ref(true)
const errorMessage = ref('')

// --- 计算属性：过滤后的用户列表 ---
const filteredUserData = computed(() => {
  const term = searchTerm.value.toLowerCase().trim()
  if (!term) return userData.map(user => ({...user, highlight: false}))

  return userData.filter(user => {
    const name = user.name || ''
    const searchString = `${user.opid.toLowerCase()} ${name.toLowerCase()}`
    return searchString.includes(term)
  }).map(user => ({...user, highlight: true}))
})

// --- 加载用户数据 ---
const loadUserData = () => {
  isLoading.value = true
  errorMessage.value = ''

  try {
    const users = normalizeUsersData()
    userData.length = 0 // 清空现有数据

    users.forEach(user => {
      userData.push({
        id: user.opid,
        opid: user.opid,
        name: user.name || '',
        role: user.role || 'user'
      })
    })

    logger.info(`已加载 ${userData.length} 个用户`)
  } catch (error) {
    errorMessage.value = `加载用户数据失败: ${error.message}`
    logger.error(errorMessage.value)
  } finally {
    isLoading.value = false
  }
}

// --- 规范化用户数据 ---
const normalizeUsersData = () => {
  try {
    const users = userStore.get('users')

    // 如果是对象格式，转换为数组
    if (users && !Array.isArray(users) && typeof users === 'object') {
      logger.info('用户数据是对象格式，转换为数组')
      const usersArray = [users]
      userStore.set('users', usersArray)
      return usersArray
    }

    // 如果数据不存在，创建默认用户
    if (!users) {
      const defaultUsers = [{
        opid: 'admin',
        password: 'admin123',
        role: 'admin',
        name: '系统管理员'
      }]
      logger.info('创建默认用户数据')
      userStore.set('users', defaultUsers)
      return defaultUsers
    }

    // 如果已经是数组，直接返回
    if (Array.isArray(users)) {
      return users
    }

    // 其他情况返回默认用户数组
    logger.warn('无法识别的用户数据格式，使用默认值')
    const defaultUsers = [{
      opid: 'admin',
      password: 'admin123',
      role: 'admin',
      name: '系统管理员'
    }]
    userStore.set('users', defaultUsers)
    return defaultUsers

  } catch (error) {
    logger.error(`规范化用户数据失败: ${error.message}`)
    return [{
      opid: 'admin',
      password: 'admin123',
      role: 'admin',
      name: '系统管理员'
    }]
  }
}

// --- 页面跳转方法 ---
const goToAddUserPage = () => {
  logger.info('跳转到新增用户页面')
  router.push('/settings/user-management/edit')
}

const goToEditUserPage = (userId) => {
  logger.info(`跳转到编辑用户页面，用户ID: ${userId}`)
  router.push(`/settings/user-management/edit/${userId}`)
}

const goToDeleteUserConfirmPage = (userId, opid) => {
  logger.info(`跳转到删除用户确认页面，用户ID: ${userId}, 工号: ${opid}`)

  // 检查是否是当前登录用户
  const currentUser = sessionStorage.getItem('loggedInUser')
  if (opid === currentUser) {
    alert('无法删除当前登录用户')
    return
  }

  // 检查是否是最后一个管理员
  const adminUsers = userData.filter(user => user.role === 'admin')
  if (adminUsers.length === 1 && adminUsers[0].opid === opid) {
    alert('无法删除最后一个管理员用户')
    return
  }

  router.push({
    path: `/settings/user-management/delete/${userId}`,
    query: {opid}
  })
}

// --- 生命周期钩子 ---
onMounted(() => {
  logger.info('用户管理列表页面已挂载')
  loadUserData()

  // 添加ESC键返回监听
  const handleEscape = (event) => {
    if (event.key === 'Escape') {
      router.back()
    }
  }
  document.addEventListener('keydown', handleEscape)

  onUnmounted(() => {
    document.removeEventListener('keydown', handleEscape)
  })
})

// --- 生命周期钩子 ---
onMounted(() => {
  logger.info('用户管理列表页面已挂载')
  // 加载用户数据
  loadUserData()
})

// 处理ESC键返回
onMounted(() => {
  const handleEscape = (event) => {
    if (event.key === 'Escape') {
      router.back()
    }
  }
  document.addEventListener('keydown', handleEscape)
  onUnmounted(() => {
    document.removeEventListener('keydown', handleEscape)
  })
})

</script>

<style scoped>
/* --- 将原始 HTML 文件中的所有自定义样式复制到这里 --- */

/* --- Inherited Styles & Color Palette --- */
/* 根变量通常在全局 CSS 中定义，但为了完整性，这里列出 */
/* :root {
  --bg-primary: #f3f4f6;
  --bg-secondary: #ffffff;
  --text-primary: #1f2937;
  --text-secondary: #6b7280;
  --text-tertiary: #9ca3af;
  --border-color: #e5e7eb;
  --accent-blue: #3b82f6;
  --status-green: #22c55e;
  --status-yellow: #eab308;
  --status-red: #ef4444;
  --status-gray: #6b7280;
  --status-off: #9ca3af;
  --online-green: #10b981;
  --offline-red: #f43f5e;
} */

/* body 样式通常由父组件或全局 App.vue 控制 */
/* body {
  font-family: 'Inter', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  background-color: var(--bg-primary);
  color: var(--text-primary);
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
} */


/* --- Header (Consistent) --- */
/* Header 样式已移至 AppHeader.vue 或全局 */


/* --- Main Content Area --- */
main {
  flex-grow: 1;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* Prevent main from scrolling, let table handle it */
  gap: 1rem;
}

.page-title {
  font-size: 1.1rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 0;
  text-align: center;
  flex-shrink: 0;
}

/* --- Top Bar (Search & Add Button) --- */
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem; /* Reduced space */
  flex-shrink: 0;
}

.filter-input-container {
  position: relative;
  width: 250px;
}

.filter-input-container i {
  position: absolute;
  left: 0.75rem;
  top: 50%;
  transform: translateY(-50%);
  color: var(--text-tertiary);
  font-size: 0.9rem;
}

#user-table-search {
  padding: 0.4rem 0.75rem 0.4rem 2.25rem;
  border: 1px solid var(--border-color);
  border-radius: 0.375rem;
  font-size: 0.8rem;
  background-color: var(--bg-secondary);
  width: 100%;
}

#user-table-search:focus {
  outline: none;
  border-color: var(--accent-blue);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
}

.hmi-button {
  padding: 0.4rem 0.8rem;
  border-radius: 0.375rem;
  font-size: 0.8rem;
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.3rem;
  border: 1px solid transparent;
  transition: all 0.2s ease;
  cursor: pointer;
}

.hmi-button i {
  font-size: 0.9em;
}

.hmi-button-primary {
  background-color: var(--accent-blue);
  color: white;
  border-color: var(--accent-blue);
}

.hmi-button-primary:hover {
  background-color: #2563eb;
  border-color: #2563eb;
}

.hmi-button-danger {
  background-color: var(--status-red);
  color: white;
  border-color: var(--status-red);
}

.hmi-button-danger:hover {
  background-color: #dc2626;
  border-color: #dc2626;
}


/* --- User Table Area --- */
.user-table-container {
  flex-grow: 1;
  overflow-y: auto;
  background-color: var(--bg-secondary);
  border-radius: 0.5rem;
  border: 1px solid var(--border-color);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.user-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.75rem;
}

.user-table th, .user-table td {
  padding: 0.6rem 0.75rem;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

.user-table th {
  background-color: #f9fafb;
  font-weight: 600;
  color: var(--text-secondary);
  position: sticky;
  top: 0;
  z-index: 10;
}

.user-table tbody tr:hover {
  background-color: #f0f4f8;
}

/* Specific column styles */
.col-opid {
  width: 150px;
  font-weight: 600;
}

.col-name { /* Takes remaining space */
}

.col-actions {
  width: 80px;
  text-align: center;
}

/* Actions column */

/* Action Buttons in Table */
.action-button {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.2rem;
  font-size: 0.9rem; /* Slightly smaller icons */
  margin: 0 0.2rem;
  transition: color 0.2s ease;
}

.action-button.edit {
  color: var(--accent-blue);
}

.action-button.edit:hover {
  color: #2563eb;
}

.action-button.delete {
  color: var(--status-red);
}

.action-button.delete:hover {
  color: #dc2626;
}


/* Highlight rows matching filter */
.user-table tbody tr.highlight {
  background-color: #e0f2fe; /* Light blue highlight */
}


/* Original body inline styles - Should be managed in App.vue or layout */
/* body[style="max-width: 800px; max-height: 600px; margin: auto;"] */
/* Remove or adapt these in your App.vue or main layout component */

</style>
